package top.ywlog.permission.util;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;


/**
 * @author Durian
 * Json工具类
 */
@Slf4j
@SuppressWarnings("unused")
public class JsonUtils
{
    private JsonUtils()
    {
    }

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private final static String FORMAT = "yyyy-MM-dd hh:mm:ss";

    static
    {
        // config
        // 对象所有字段全部列入
        OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 取消默认转换的timestamps
        OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // 忽略空bean转换json错误
        OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 统一日期格式
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat(FORMAT));
        // 忽略在json中存在，bean中不存在的属性
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> String obj2String(T src)
    {
        if (src == null)
        {
            return null;
        }
        try
        {
            return src instanceof String ? (String) src : OBJECT_MAPPER.writeValueAsString(src);
        } catch (Exception e)
        {
            log.warn("parse Object to JSON String error : {}", e.getMessage());
            return null;
        }
    }

    public static <T> T string2Obj(String src, TypeReference<T> typeReference)
    {
        if (src == null || typeReference == null)
        {
            return null;
        }
        try
        {
            return (T) (typeReference.getType().equals(String.class) ? src : OBJECT_MAPPER.readValue(src, typeReference));
        } catch (Exception e)
        {
            log.warn("parse JSON String to Object error : {}, TypeReference<T>:{}, error:{}",
                    src, typeReference.getType(), e.getMessage());
            return null;
        }
    }


}
